package eBrain.model;

import java.io.File;
import java.text.DateFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.catalina.Session;
import org.apache.commons.fileupload.*;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;

import com.sun.org.apache.bcel.internal.generic.GETSTATIC;

import eBrain.beans.CategorySales;
import eBrain.beans.Item;
import eBrain.beans.Sales;
import eBrain.beans.User;

public class ActionHandler {

	public static String storeBid(HttpServletRequest request){
		HttpSession session = request.getSession();
        Item item = (Item)session.getAttribute("itemInfo");
        User user = (User)session.getAttribute("validUser");
        
        if (isLoggedIn(request)){
        
        double bidvalue = Double.valueOf(request.getParameter("bidvalue")).doubleValue();
        DataManager dataManager = (DataManager)session.getServletContext().getAttribute("dataManager");
        BidWorker bw = new BidWorker(item, user, dataManager, bidvalue);
        	if(bw.validateBid()){
        		dataManager.setBid(bw.getNewMaxBid());
        		request.setAttribute("msg", "Congratulation, you are the highest bidder");
        		session.setAttribute("itemInfo",item);	
        		return "item.jsp";
        	}
        	else {
        		
        		request.setAttribute("msg", "Bid was not accepted. Minimum bid is: " + bw.getMinBidValue());
        		return "setBid.jsp";
        	}
	}
        
        return "login.jsp";
	}
	
	public static String storeItem(HttpServletRequest request){
		
		try {
			HttpSession session = request.getSession();
			DataManager dataManager = (DataManager)session.getServletContext().getAttribute("dataManager");
			User user = (User)session.getAttribute("validUser");
			Item item = new Item();
			item.setUserid(user.getUser_id());
			item.setName(request.getParameter("name"));
			DateFormat formatter = DateFormat.getDateTimeInstance(); 
			Date d  = formatter.parse(request.getParameter("startdate")+" "+request.getParameter("starttime")); 
			item.setStart(d);
			d  = formatter.parse( request.getParameter("enddate")+" "+request.getParameter("endtime"));
			item.setEnd(d);
			item.setStartBid(Double.valueOf(request.getParameter("startBid")).doubleValue());
			item.setDescription(request.getParameter("description")); 
			dataManager.setItem(item);
			session.setAttribute("itemInfo", item);
		} catch (Exception e) {
			// TODO Auto-generated catch block	
			e.printStackTrace();
			return "index.jsp";
		}
		
		return "item.jsp";
	}

	public static boolean isLoggedIn(HttpServletRequest request) {
		
		HttpSession session = request.getSession();
		Enumeration <String> e = session.getAttributeNames();
		while (e.hasMoreElements()){
			if(e.nextElement().equals("validUser")){
				return true;
			}
		}
		return false;
	}

	public static String doLogin(HttpServletRequest request){
		
		HttpSession session = request.getSession();
		DataManager dataManager = (DataManager)session.getServletContext().getAttribute("dataManager");
		
		
		String UserName = request.getParameter("userName");
		String Password = request.getParameter("password");
		if (!dataManager.validatePassword(UserName, Password)) {
			request.setAttribute("msg", "The User Name or Password you entered is not valid.");
			return "login.jsp";
		}
		else{
		session.setAttribute("validUser", dataManager.getUserByUserName(UserName));
		session.setMaxInactiveInterval(1200000);
		return "";
		}
		
		
	}
	
	public static boolean doLogout(HttpServletRequest request){
	
		HttpSession session = request.getSession();
		try {
			session.invalidate();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}
		return true; 
	}
	
	public static boolean doSales(HttpServletRequest request){
		HttpSession session = request.getSession();
		SalesWorker salesWorker = new SalesWorker((User)session.getAttribute("validUser"),(DataManager)session.getServletContext().getAttribute("dataManager"));		
		Sales sales = SalesWorker.getSales();
		if(sales==null){
			request.setAttribute("salesmsg", "Sorry an error occorred at calculating your sales statistic");
			return false; 
		}
		session.setAttribute("sales", sales);
		return true;
	}

	public static void openItem(HttpServletRequest request) {
		HttpSession session = request.getSession();
		DataManager dataManager = (DataManager)session.getServletContext().getAttribute("dataManager");
		Item item = (Item)dataManager.getItem(request.getParameter("id"));
		session.setAttribute("itemInfo",item);	
	}
	public static String openUser(HttpServletRequest request){
		if(isLoggedIn(request))return "updateUser.jsp";
		else return "login.jsp";
	}

	public static String updateUser(HttpServletRequest request) throws ParseException {
		HttpSession session = request.getSession();
		DataManager dataManager = (DataManager)session.getServletContext().getAttribute("dataManager");
		User user = (User)session.getAttribute("validUser");
		User temp = new User();
		temp.setUser_id(user.getUser_id());
		temp.setUsername(request.getParameter("username"));
		temp.setFirstname(request.getParameter("firstname"));
		temp.setLastname(request.getParameter("lastname"));
		temp.setPassword(user.getPassword());
		temp.setEmail(request.getParameter("email"));
		temp.setGender(request.getParameter("gender"));
		DateFormat formatter = DateFormat.getDateTimeInstance();
		Date d  = formatter.parse(request.getParameter("birthday")+" 00:00:00");
		temp.setBirthday(d);
		temp.setStreet(request.getParameter("street"));
		temp.setCity(request.getParameter("city"));
		temp.setZIP(request.getParameter("ZIP"));
		temp.setCountry(request.getParameter("country"));
		
//		if(user.equals(temp)){
//			return "updateUser.jsp";
//		}
//		
		dataManager.updateUser(temp);
		
		return "updateUser.jsp";
	}

	public static String openSalesStat(HttpServletRequest request) {
		
		HttpSession session = request.getSession();
		DataManager dataManager = (DataManager)session.getServletContext().getAttribute("dataManager");
		User user = (User)session.getAttribute("validUser");
		
		if (user.getUsername().equals("mar.wuestemann")){
			ArrayList<CategorySales> allCatSales = new ArrayList<CategorySales>();
			if(request.getParameter("categoryselectedname")!=null){
				SalesWorker salesWorker = new SalesWorker(dataManager.getUserByUserName(request.getParameter("categoryselectedname")),dataManager,dataManager.getItemsByCategory(request.getParameter("categoryselectedname")));		
				CategorySales salesCategory  = salesWorker.getSalesForCategory();
				request.setAttribute("categoryQuery", salesCategory);
				request.setAttribute("selectedCategory", request.getParameter("categoryselectedname"));
				}
		else{ 
				Hashtable<String,String> cats = dataManager.getAllCategories();
				Enumeration<String> categoryIds = cats.keys();
			     while (categoryIds.hasMoreElements()) {
			          String categoryId = (String)categoryIds.nextElement();
			          SalesWorker salesWorker = new SalesWorker((User)session.getAttribute("validUser"),dataManager,dataManager.getItemsByCategory(categoryId));
			          CategorySales catSales = salesWorker.getSalesForCategory();
			          catSales.setCategoryName(cats.get(categoryId));
			          allCatSales.add(catSales);
			          request.setAttribute("categoryAll", allCatSales);
			     }
			}
			
			
			if(request.getParameter("userselectedname")!=null){
			System.out.println(request.getParameter("userselectedname"));	
			SalesWorker salesWorker = new SalesWorker(dataManager.getUserByUserName(request.getParameter("userselectedname")),dataManager);		
			Sales sales = SalesWorker.getSales();
			request.setAttribute("salesQuery", sales);
			request.setAttribute("selectedUser", request.getParameter("userselectedname"));
			}
			
			
			
			return "saleStat.jsp";
		}
		
		return "index.jsp";
		
		
	}
	
	public static String addUser(HttpServletRequest request) throws ParseException {
		User user = new User();
		HttpSession session = request.getSession();
		DataManager dataManager = (DataManager)session.getServletContext().getAttribute("dataManager");
		
		user.setUsername(request.getParameter("username"));
		user.setFirstname(request.getParameter("firstname"));
		user.setLastname(request.getParameter("lastname"));
		user.setEmail(request.getParameter("email"));
		user.setGender(request.getParameter("gender"));
		user.setPassword(request.getParameter("password"));
		DateFormat formatter = DateFormat.getDateTimeInstance();
		Date d = formatter.parse(request.getParameter("birthday")+" 00:00:00");
		user.setBirthday(d);
		user.setStreet(request.getParameter("street"));
		user.setCity(request.getParameter("city"));
		user.setZIP(request.getParameter("ZIP"));
		user.setCountry(request.getParameter("country"));
	
		if(dataManager.setUser(user)==true){
			return "index.jsp";
		}
		
		return "AddUser.jsp";
	}
	
}